#define _CRT_SECURE_NO_WARNINGS
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* head = new ListNode(0);
        ListNode* cur = head;
        int sum = 0, carray = 0;
        while (l1 != nullptr || l2 != nullptr)
        {
            int num = (l1 == nullptr ? 0 : l1->val) + (l2 == nullptr ? 0 : l2->val) + carray;
            sum = num % 10;
            carray = num / 10;
            if (l1 != nullptr)
            {
                l1 = l1->next;
            }
            if (l2 != nullptr)
            {
                l2 = l2->next;
            }
            cur->next = new ListNode(sum);
            cur = cur->next;
        }
        if (carray != 0)
        {
            cur->next = new ListNode(carray);
        }
        return head->next;
    }
};